<template>
  <section class="content">
    <div class="header">
      <div class="titleSty">开通电子印章服务</div>
    </div>
    <div class="labelSty">
      <span class="required">*</span>请下载申请书模板，填写申请书内容并加盖公章后上传照片
      <el-button class="required ml20"
                 type="text"
                 @click="downloadTemplate">下载模板</el-button>
      <el-button class="required ml30"
                 type="text"
                 @click="visible=true; idCard=false;">示例</el-button>
    </div>
    <div class="mt20 ml20 uploadSty">
      <seal-upload type="png"
                   :cert-type="2"
                   :position="1"
                   :attaches="attaches1"
                   :is-look="applyDetails && applyDetails.auditStatus === 1 && applyDetails.payStatus === 1"
                   @uploadSuccess="uploadSuccess"
                   @removeFile="removeFile" />
      <div class="reason_sty">
        <div v-if="reason1.length">
          <template v-for="(ele, i) in reason1">
            <div :key="i"
                 class="reason_label">
              <div class="dot"></div>{{ele}}
            </div>
          </template>
        </div>
        <p class="uploadlableSty">上传图片只能是JPG、JPEG、gif、bmp、PNG格式，单个文件不能超过3MB!</p>
      </div>
    </div>
    <div class="mt10 ml50">申请书</div>
    <div class="labelSty mt30">
      <span class="required">*</span>上传经办人身份证照片
      <span class="required ml20"
            @click="visible=true; idCard=true;">示例</span>
    </div>
    <div class="mt20 ml20 uploadSty">
      <seal-upload type="png"
                   :cert-type="2"
                   :position="2"
                   :attaches="attaches2"
                   :is-look="applyDetails && applyDetails.auditStatus === 1 && applyDetails.payStatus === 1"
                   @uploadSuccess="uploadSuccess"
                   @removeFile="removeFile" />
      <seal-upload type="png"
                   class="ml20"
                   :cert-type="2"
                   :position="3"
                   :attaches="attaches3"
                   :is-look="applyDetails && applyDetails.auditStatus === 1 && applyDetails.payStatus === 1"
                   @uploadSuccess="uploadSuccess"
                   @removeFile="removeFile" />
      <div class="reason_sty">
        <div v-if="reason2.length">
          <template v-for="(ele, i) in reason2">
            <div :key="i"
                 class="reason_label">
              <div class="dot"></div>{{ele}}
            </div>
          </template>
        </div>
        <p class="uploadlableSty">上传图片只能是JPG、JPEG、gif、bmp、PNG格式，单个文件不能超过3MB!</p>
      </div>
    </div>
    <div class="mt10 uploadSty">
      <div class="ml30">身份证人像页</div>
      <div class="ml30">身份证国徽页</div>
    </div>
    <div class="labelSty mt50">开通电子印章需使用微信支付<span class="required">100元/年</span>使用费，电子印章有效期为一年：自审核通过之日起算。</div>
    <el-button v-if="!applyDetails || (applyDetails && applyDetails.auditStatus != 1 || applyDetails.payStatus != 1)"
               class="mt50 ml20"
               type="primary"
               @click="submit">{{applyDetails && applyDetails.auditStatus=== 3 ? '提交资料':'提交并支付'}}</el-button>
    <el-button class="mt50 ml20"
               @click="back">返回</el-button>
    <application-dialog v-if="visible"
                        :visible.sync="visible"
                        :id-card="idCard" />
    <el-dialog :visible="payVisible"
               :before-close="close"
               :close-on-click-modal="false"
               top="18vh"
               width="20%"
               append-to-body
               title="微信支付">
      <div class="all-center">
        <div>
          <span>请使用微信扫一扫扫描二维码支付</span>
          <p v-if="countDown===0"
             style="text-align: center;">请手动刷新二维码</p>
          <p v-else
             style="text-align: center;">{{countDown}}秒后需手动刷新</p>
          <img width="180"
               height="180"
               :src="'data:image/png;base64,'+codeUrl"
               :class="countDown===0?'img_opacity':'img_sty'" />
          <el-button v-if="countDown===0"
                     class="refresh"
                     round
                     type="primary"
                     icon="el-icon-refresh"
                     @click="refresh">刷新二维码</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog :visible="payResult"
               :before-close="close"
               :close-on-click-modal="false"
               top="20vh"
               width="20%"
               append-to-body
               title="微信支付">
      <div class="pay_success">
        <i class="el-icon-success pay_success_icon"></i>
        <p style="text-align: center;">支付成功！</p>
        <el-button type="primary"
                   @click="back">我知道了</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import SealUpload from "./SealUpload.vue";
import ApplicationDialog from "./ApplicationDialog.vue";
import { seal, wxapi } from "@/api/index.js";
import { mapState } from "vuex";
export default {
  name: "OpenApplication",
  components: {
    SealUpload,
    ApplicationDialog
  },
  data () {
    return {
      visible: false,   // 示例显示
      payVisible: false, //微信支付二维码显示
      code: null,
      codeUrl: null, //微信支付二维码
      countDown: 60,  // 倒计时
      payResult: false, //是否已扫码支付
      timer: null,
      payTimer: null,  //定时器
      applyDetails: null,
      attachments: [],
      attaches1: [],
      attaches2: [],
      attaches3: [],
      reason1: [],
      reason2: [],
      templateUrl: `/excelTemplate/电子印章申请表.doc`,
      userInfo: sessionStorage.getItem('userInfo')
    };
  },
  computed: {
    ...mapState({
      // login: (state) => state.login
      login () {
        return JSON.parse(this.userInfo)
      }
    }),
    applyId () {
      return this.$route.query.applyId
    },
    // 1 开通 2续费
    applyType () {
      return this.$route.query.applyType
    }
  },
  created () {
    if (this.applyId)
      this.getApplyDetails();
  },
  methods: {
    // 获取详情
    async getApplyDetails () {
      let { data } = await seal.getApplyDetails(this.applyId);
      this.applyDetails = data
      this.attachments = data.attachments
      if (data.attachments.length) {
        data.attachments.forEach(item => {
          const { position } = item;
          this[`attaches${position}`] = [{ ...item }];
        });
      }
      // data.attachments.length && data.attachments.map(item => {
      //   if (item.position === 1) this.attaches1 = [{ ...item }]
      //   if (item.position === 2) this.attaches2 = [{ ...item }]
      //   if (item.position === 3) this.attaches3 = [{ ...item }]
      // })
      if (data.refusalReason && data.refusalReason.length) {
        data.refusalReason.map(item => {
          if (["申请书内容不清晰", "公司名称与申请书不一致"].includes(item))
            this.reason1.push(item)
          else
            this.reason2.push(item)
        })
      }
    },
    // 下载模板
    downloadTemplate () {
      this.$tools.orderDownload(this.templateUrl)
    },
    // 上传附件
    uploadSuccess (data) {
      if (this.attachments.length) {
        let flag = true
        this.attachments.map(item => {
          if (item.position === data[0].position) {
            flag = false
            item.name = data[0].name
            item.url = data[0].url
          }
        })
        if (flag) this.attachments.push({ ...data[0] })
      } else {
        this.attachments = [...data]
      }
    },
    // 删除附件
    removeFile (data) {
      if (this.attachments.length) {
        let index = null
        this.attachments.map((item, i) => {
          if (item.name === data.name && item.position === data.position) {
            index = i
          }
        })
        this.attachments.splice(index, 1)
      }
    },
    // 触发事件
    async submit () {
      if (this.attachments.length < 3) {
        return this.$message.warning("请上传相应文件")
      }
      this.countDown = 60;
      clearInterval(this.payTimer);
      if (this.applyType === '2' || !this.applyId) {
        let response = await seal.create({
          applyType: this.applyType,
          attachments: this.attachments,
        })
        const { data } = response
        if (data) {
          this.payVisible = true;
          this.code = data;
          this.getPayCode(data)
        }
      } else {
        let response = await seal.update({
          applyId: this.applyId,
          attachments: this.attachments,
        })
        const { data } = response
        if (this.applyDetails.payStatus === 2) {
          this.payVisible = true;
          this.code = data;
          this.getPayCode(data)
        } else {
          this.$router.back()
        }
      }
    },
    // 微信支付二维码
    async getPayCode (id) {
      let response = await wxapi.createPayQrCode({
        id,
        productId: id,
        extType: 1,
        totalFee: 10000,
        companyName: this.login.tenantName,
      });
      const { data } = response
      this.codeUrl = data.base64;
      this.handleCountDown()
      this.refreshWxPayStatus(data.outTradeNo)
    },
    // 支付倒计时
    handleCountDown () {
      this.payTimer = setInterval(() => {
        if (this.countDown > 0) {
          this.countDown -= 1
        }
      }, 1000);
    },
    // 支付结果刷新
    refreshWxPayStatus (outTradeNo) {
      this.timer = setInterval(() => {
        if (this.countDown > 0 && !this.payResult && this.payVisible) {
          this.getWxPayStatus(outTradeNo)
        }
      }, 5000);
    },
    async getWxPayStatus (outTradeNo) {
      let response = await wxapi.getWxPayStatus(outTradeNo);
      const { data } = response
      this.payResult = data
    },
    // 返回
    back () {
      this.$router.back();
    },
    // 刷新
    refresh () {
      this.countDown = 60
      this.getPayCode(this.code)
    },
    // 取消
    close () {
      this.payVisible = false;
    },
    beforeDestroy () {
      clearInterval(this.timer);
      clearInterval(this.payTimer);
    },
  }
};
</script>
<style lang="scss" scoped>
.content {
  background: var(--prev-bg-white);
  padding: 20px;
  position: relative;
  height: 88vh;
}
.body {
  height: 80vh;
  overflow-x: hidden;
}
.titleSty {
  width: 200px;
  height: 16px;
  border-left: 2px solid var(--prev-color-primary);
  padding-left: 6px;
  margin-top: 10px;
  font-size: 16px;
  font-weight: 500;
}
.mt10 {
  margin-top: 10px;
}
.mt20 {
  margin-top: 20px;
}
.mt30 {
  margin-top: 30px;
}
.mt50 {
  margin-top: 50px;
}
.ml20 {
  margin-left: 20px;
}
.ml30 {
  margin-left: 30px;
}
.ml50 {
  margin-left: 50px;
}
.ml290 {
  margin-left: 290px;
}
.header {
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
.labelSty {
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 400;
  line-height: 20px;
  color: var(--prev-color-text-darkgrey);
  opacity: 1;
  margin-left: 20px;
}
.required {
  color: var(--prev-color-primary);
}
.uploadSty {
  display: flex;
  justify-content: flex-start;
  align-items: flex-end;
}
.uploadlableSty {
  font-size: 12px;
  font-family: PingFang SC;
  font-weight: 400;
  line-height: 17px;
  color: var(--prev-color-text-grey);
  opacity: 1;
}
.all-center {
  display: flex;
  justify-content: center;
  align-items: center;
}
.img_sty {
  margin-left: 12px;
}
.img_opacity {
  opacity: 0.03;
  margin-left: 12px;
}
.refresh {
  position: absolute;
  top: 60%;
  right: 36%;
}
.reason_sty {
  display: flex;
  flex-direction: column;
  color: var(--prev-color-text-red);
  font-size: 14px;
  margin-left: 20px;
}
.reason_label {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  line-height: 36px;
}
.dot {
  width: 6px;
  height: 6px;
  background: var(--prev-color-text-red);
  border-radius: 100%;
  opacity: 1;
  margin-right: 10px;
}
.pay_success {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.pay_success_icon {
  font-size: 120px;
  color: #07c160;
}
</style>
